#!/usr/bin/env bash

# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if (( $# < 2)); then
  echo "Getting $* $#"
  echo "Bad parameters. Usage example: bash get_python_packages /tmp/analytics_zoo_python/ 0.7.2"
  exit -1
fi

DEST_DIR=$1
echo "DEST_DIR: $DEST_DIR"
BIGDL_VERSION=$2
NLP_ARCHITECT_VERSION="0.3.1"
# Since bert doesn't have any released versions, use the version of the commit on Mar 29, 2019.
BERT_COMMIT_ID="d66a146741588fb208450bde15aa7db143baaa69"

rm -rf $DEST_DIR/*/

echo "Fetching BigDL ${BIGDL_VERSION}"
GET_COMMAND="mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DartifactId=dist-spark-2.2.0-scala-2.11.8-all \
-DgroupId=com.intel.analytics.bigdl \
-Dversion=${BIGDL_VERSION} \
-Dclassifier=python-api \
-Dpackaging=zip \
-Ddest=${DEST_DIR}/bigdl-python-api-${BIGDL_VERSION}.zip"
echo "Running: $GET_COMMAND"
$GET_COMMAND
exit_status=$?
if [ $exit_status -ne 0 ];
then
    rm -rf ${DEST_DIR}
    echo "Failed to get BigDL Python API from Maven."
    exit $exit_status
fi

echo "Fetching nlp-architect ${NLP_ARCHITECT_VERSION}"
if [ $FTP_URI ];
then
    PREFIX="$FTP_URI/nlp_architect"
else
    PREFIX=https://github.com/NervanaSystems/nlp-architect/archive

fi
GET_COMMAND="wget -nc $PREFIX/v${NLP_ARCHITECT_VERSION}.zip -P $DEST_DIR"
echo "Running: $GET_COMMAND"
$GET_COMMAND
exit_status=$?
if [ $exit_status -ne 0 ];
then
    rm -rf ${DEST_DIR}
    echo "Failed to get nlp-architect package from GitHub."
    exit $exit_status
fi

echo "Fetching bert with ${BERT_COMMIT_ID}"
if [ $FTP_URI ];
then
    PREFIX="$FTP_URI/bert"
else
    PREFIX=https://github.com/google-research/bert

fi

GET_COMMAND="wget -nc $PREFIX/archive/${BERT_COMMIT_ID}.zip -P $DEST_DIR"
echo "Running: $GET_COMMAND"
$GET_COMMAND
exit_status=$?
if [ $exit_status -ne 0 ];
then
    rm -rf ${DEST_DIR}
    echo "Failed to get bert package from GitHub."
    exit $exit_status
fi

cd ${DEST_DIR}
mkdir sources
unzip -q bigdl-python-api-${BIGDL_VERSION}.zip -d sources

unzip -q v${NLP_ARCHITECT_VERSION}.zip -d sources
cd sources/nlp-architect-${NLP_ARCHITECT_VERSION}
mv nlp_architect/ ../
cd ${DEST_DIR}
rm -rf sources/nlp-architect-${NLP_ARCHITECT_VERSION}

unzip -q ${BERT_COMMIT_ID}.zip -d sources
cd sources
mv bert-${BERT_COMMIT_ID}/ bert/
